package com.yanhao.etx

import com.google.gson.Gson
import com.yanhao.bean.WanResult
import com.yanhao.etx.ErrorMsg.CANCELLATIONEXCEPTION
import com.yanhao.etx.ErrorMsg.CONNECTEXCEPTION
import com.yanhao.etx.ErrorMsg.DATAERROR
import com.yanhao.etx.ErrorMsg.SERVERERROR
import com.yanhao.etx.ErrorMsg.TIMEOUT
import com.yanhao.etx.ErrorMsg.UNKNOWNERROR
import org.json.JSONException
import retrofit2.HttpException
import java.io.InterruptedIOException
import java.net.ConnectException
import java.net.UnknownHostException
import java.util.concurrent.CancellationException

object ErrorMsg {
    val TIMEOUT = "服务器连接超时"
    val TOKENOUT = "Token失效"
    val SERVERERROR = "服务器连接失败"
    val DATAERROR = "数据异常"
    val CONNECTEXCEPTION = "连接错误"
    val CANCELLATIONEXCEPTION = "运行异常"
    val UNKNOWNERROR = "未知错误"
}

data class ErrorData(val code: Int, val msg: String)

inline fun Throwable.error(): ErrorData? {
    val result = when (this) {
        is HttpException -> {
            var errorBody = this.response()?.errorBody()
            var errorJson = errorBody?.string()
            val result = Gson().fromJson(errorJson, WanResult::class.java)
            ErrorData(result.errorCode, result.errorMsg)
        }
        is InterruptedIOException -> {
            ErrorData(500, TIMEOUT)
        }
        is UnknownHostException -> {
            ErrorData(-1, SERVERERROR)
        }
        is JSONException -> {
            ErrorData(-1, DATAERROR)
        }
        is ConnectException -> {
            ErrorData(-1, CONNECTEXCEPTION)
        }
        /**
         * 如果协程还在运行，个别机型退出当前界面时，viewModel会通过抛出CancellationException，
         * 强行结束协程，与java中InterruptException类似，所以不必理会,只需将toast隐藏即可
         */
        is CancellationException -> {
            ErrorData(-1, CANCELLATIONEXCEPTION)
        }
        else -> ErrorData(-1, UNKNOWNERROR)
    }
    return result
//    if (this is HttpException) {
//        var errorBody = this.response()?.errorBody()
//        var errorJson = errorBody?.string()
//        val result = Gson().fromJson(errorJson, WanResult::class.java)
//        return ErrorData(result.errorCode, result.errorMsg)
//    } else if (this is InterruptedIOException) {
//        return ErrorData(500, TIMEOUT)
//    } else if (this is UnknownHostException) {
//        return ErrorData(-1, SERVERERROR)
//    }
//    //后续别的异常这里继续添加
//    return ErrorData(-1, SERVERERROR)
}